/**
 * FileName: TokenUtil
 * Author:   Leopold
 * Date:     2018/9/3 19:33
 * Description: 生成token和解密token
 * History:
 */
package cn.mcsys.viewer.core.utils;

//import com.auth0.jwt.JWT;
//import com.auth0.jwt.JWTVerifier;
//import com.auth0.jwt.algorithms.Algorithm;
//import com.auth0.jwt.interfaces.Claim;
//import com.auth0.jwt.interfaces.DecodedJWT;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

public class TokenUtil {

    public static final String SIGN = "GZMCSYSToken";

    public static final String UID = "uid";

    public static String createToken(String key, String value){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        String token = null;//加密
        try {
            token = JWT.create()
                    .withHeader(map)//header
                    .withClaim(key, value)//payload
                    .sign(Algorithm.HMAC256(SIGN));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 用于拦截器做数据校验
     * @param key
     * @param token
     * @return
     * @throws Exception
     */
    public static String verifyToken(String key, String token) throws Exception {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SIGN))
                .build();
        DecodedJWT jwt = verifier.verify(token);
        Map<String, Claim> claims = jwt.getClaims();
        return claims.get(key).asString();
    }


}
